package com.xjd.edu.mybatis;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.MDC;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 分页查询检查拦截器
 *
 * @author wangyu
 * @since 2025/3/15 13:49
 */
@Slf4j
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class CheckQueryLimitInterceptor implements Interceptor {

    private static final Map<String, Counter> CACHE = new HashMap<>();

    /**
     * 默认检查分页长度上限
     */
    final int DEFAULT_MAX_PAGE_SIZE = 10_000;

    final String HEADER_REQUEST_URI_NAME = "X-Request-Uri";

    private Properties properties;
    private final MeterRegistry registry;

    public CheckQueryLimitInterceptor() {
        this(new Properties());
    }

    public CheckQueryLimitInterceptor(Properties properties) {
        this(new Properties(), null);
    }

    public CheckQueryLimitInterceptor(MeterRegistry registry) {
        this(new Properties(), registry);
    }

    public CheckQueryLimitInterceptor(Properties properties, MeterRegistry registry) {
        Assert.notNull(properties, "属性参数不能为空");
        this.properties = properties;
        this.registry = registry;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        final Object result = invocation.proceed();
        try {
            checkResultSize(invocation, result);
        } catch (Exception e) {
            log.error("检查分页出错", e);
        }
        return result;
    }

    private void checkResultSize(Invocation invocation, Object result) {
        if (result == null) {
            return;
        }

        int rows;
        if (result instanceof Collection) {
            rows = ((Collection<?>) result).size();
        } else if (result instanceof Map) {
            rows = ((Map<?, ?>) result).size();
        } else {
            return;
        }

        // 判断分页大于指定长度时，打印相关信息
        final int maxPageSize = this.getMaxPageSize();
        if (rows <= maxPageSize) {
            return;
        }

        final String from = Optional.ofNullable(MDC.get(HEADER_REQUEST_URI_NAME)).orElse("unknown");

        final Object[] args = invocation.getArgs();

        // 容错处置，避免潜在的空指针风险
        if (args == null || args.length == 0 || !(args[0] instanceof MappedStatement)) {
            log.warn("查询长度超限 rows: {}/{}, from: {}", rows, maxPageSize, from);
            return;
        }

        final MappedStatement statement = (MappedStatement) args[0];

        // 计数监控
        if (registry != null) {
            counter(statement.getId()).increment();
        }

        // 生成日志文本
        final StringBuilder builder = new StringBuilder(String.format("[%s] 查询长度超限 rows: %d/%d, from: %s",
                statement.getId(), rows, maxPageSize, from));
        if (args.length > 1) {
            final BoundSql boundSql = statement.getBoundSql(args[1]);
            builder.append(" => ").append(boundSql.getSql());
        }
        log.warn(builder.toString());

    }

    /**
     * 对 counter 实例进行缓存
     *
     * @param id 非空
     * @return
     */
    private Counter counter(String id) {
        return CACHE.computeIfAbsent(id, key ->
                Counter.builder("game.page.overflow")
                        .description("查询长度超限")
                        .tag("id", key)
                        .tag("type", "mysql")
                        .register(registry)
        );
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    private Integer getMaxPageSize() {
        return Math.min(DEFAULT_MAX_PAGE_SIZE, (Integer) properties.getOrDefault("maxPageSize", DEFAULT_MAX_PAGE_SIZE));
    }
}
